﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Globalization;
using System.Linq;
using System.Web.UI.WebControls;
using System.Web.Security;
using ELearningSystem.UI.ContentServiceReference;
using Answer = ELearningSystem.UI.PracticeServiceReference.AnswerDAO;
using ContentDAO = ELearningSystem.UI.ContentServiceReference.ContentDAO;
using ContentManager = ELearningSystem.UI.ContentServiceReference.ContentServiceSoapClient;
using PracticeDAO = ELearningSystem.UI.PracticeServiceReference.PracticeDAO;
using PracticeManager = ELearningSystem.UI.PracticeServiceReference.PracticeServiceSoapClient;
using VideoContentDAO = ELearningSystem.UI.ContentServiceReference.VideoContentDAO;
using UserManager = ELearningSystem.UI.LearnerServiceReference.LearnerServiceSoapClient;
using LearnerDAO = ELearningSystem.UI.LearnerServiceReference.LearnerDAO;
using ScoreViewDAO = ELearningSystem.UI.LearnerServiceReference.ScoreViewDAO;
using AttemptDAO = ELearningSystem.UI.LearnerServiceReference.AttemptDAO;

namespace ELearningSystem.UI.UserUI
{
    public partial class UserHomePageUI : System.Web.UI.Page
    {
        protected string contentLink;
        private ContentManager contentManager = new ContentManager();
        private PracticeManager practiceManager = new PracticeManager();
        private UserManager userManager = new UserManager();

        protected void Page_Load(object sender, EventArgs e)
        {
            commentsTextBox.Enabled = false;
            saveCommentButton.Enabled = false;
            signInLinkButton.Visible = true;
            signUpLinkButton.Visible = true;
            signOutlinkButton.Visible = false;
            
            if (!IsPostBack)
            {
                ClearViewControls();
                InitializeTree();
                playlistTreeView.Nodes[0].ChildNodes[0].ChildNodes[0].Selected = true;
                TreeNode selectedNode = playlistTreeView.SelectedNode;
                RenderControls(selectedNode);
                selectedNode.Selected = true;
                RenderForNextAndPreviousButton(selectedNode);
            }

            if (Request.IsAuthenticated)
            {
                userHomeLabel.Text = "Welcome, "+User.Identity.Name;
                commentsTextBox.Enabled = true;
                saveCommentButton.Enabled = true;
                signInLinkButton.Visible = false;
                signUpLinkButton.Visible = false;
                signOutlinkButton.Visible = true;
                LearnerDAO aLearner = userManager.GetLearnerWithName(User.Identity.Name);
                ScoreViewDAO score = userManager.GetUpdatedScore(aLearner);
                PopulateUserScore(score);
            }
        }

        private void ClearViewControls()
        {
            userHomeLabel.Text = "";
            questionResponseLabel.Text = "";
            totalPracticeLabel.Text = "";
            attemptedOnTotalLabel.Text = "";
            pasedOnAttempted.Text = "";
            passedOnTotal.Text = "";
            score_div.Visible = false;
        }

        private void PopulateUserScore(ScoreViewDAO score)
        {
            score_div.Visible = true;
            totalPracticeLabel.Text = score.TotalPractices.ToString(CultureInfo.InvariantCulture);
            attemptedOnTotalLabel.Text = score.AttemptedOnTotal.ToString(CultureInfo.InvariantCulture);
            pasedOnAttempted.Text = score.PassedOnAttempted.ToString(CultureInfo.InvariantCulture);
            passedOnTotal.Text = score.PassedOnTotal.ToString(CultureInfo.InvariantCulture);
        }

        protected void saveCommentButton_Click(object sender, EventArgs e)
        {
            if (Request.IsAuthenticated)
            {
                TreeContentDAO treeContent = contentManager.GetTreeContent(int.Parse(playlistTreeView.SelectedNode.Value));
                LearnerDAO learner = new LearnerDAO();
                learner = userManager.GetLearnerWithName(User.Identity.Name);
                CommentDAO comment = new CommentDAO();
                comment.Date = DateTime.Now;
                comment.Learner = learner;
                comment.Text = commentsTextBox.Text;
                treeContent.Content.Video.Comments.Add(comment);
                contentManager.SaveOrUpdate(treeContent);
                RenderControls(playlistTreeView.SelectedNode); 
            }
            
        }

        protected void signInLinkButton_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/UserUI/UserLoginUI.aspx");
        }

        protected void playlistTreeView_SelectedNodeChanged(object sender, EventArgs e)
        {
            TreeNode selectedNode = playlistTreeView.SelectedNode;
            selectedNode.Selected = false;
            selectedNode.ToggleExpandState();
            TreeNode currentNodeToSelect = RecursiveCheckForChild(selectedNode);
            RenderControls(currentNodeToSelect);
            currentNodeToSelect.Selected = true;
            RenderForNextAndPreviousButton(currentNodeToSelect);
        }

        private void RenderForNextAndPreviousButton(TreeNode selectedNode)
        {
          
            RenderNextButton(selectedNode);
            RenderPriviousButton(selectedNode);
        }

        private void RenderPriviousButton(TreeNode selectedNode)
        {
            questionResponseLabel.Text = "";
            TreeNode previousNode =
                playlistTreeView.FindNode(contentManager.GetPreviousTreeNodePath(selectedNode.Value, treeDataSource.Data));
            
            if (selectedNode!=previousNode)
            {
                previousButton.Enabled = true;
                previousButton.BackColor = Color.Green;
                previousButton.ForeColor = Color.White;
                
            }
            else
            {
                previousButton.Enabled = false;
                previousButton.BackColor = Color.Gray;
                previousButton.ForeColor = Color.Green;
                
            }
            
        }

        private void RenderNextButton(TreeNode selectedNode)
        {
            questionResponseLabel.Text = "";
            TreeNode nextNode =
              playlistTreeView.FindNode(contentManager.GetNextTreeNodePath(selectedNode.Value, treeDataSource.Data));
            if (selectedNode != nextNode)
            {
                nextButton.Enabled = true;
                nextButton.BackColor = Color.Green;
                nextButton.ForeColor = Color.White;
            }
            else
            {
                nextButton.Enabled = false;
                nextButton.BackColor = Color.Gray;
                nextButton.ForeColor = Color.Green;
            }
        }

        private TreeNode RecursiveCheckForChild(TreeNode node)
        {
            if (!(node.ChildNodes.Count>0))
            {
                return node;
            }
            return RecursiveCheckForChild(node.ChildNodes[0]);
            
        }

        private void InitializeTree()
        {
            treeDataSource.Data = contentManager.GetTreeDataSource();
            playlistTreeView.DataBindings.Add(new TreeNodeBinding() { DataMember = "CATEGORY", TextField = "name", ValueField = "ID" });
            playlistTreeView.DataBindings.Add(new TreeNodeBinding() { DataMember = "CONTENT", TextField = "name", ValueField = "ID" });
            playlistTreeView.DataBindings.Add(new TreeNodeBinding() { DataMember = "TOPIC", TextField = "name", ValueField = "ID" });

            playlistTreeView.DataBind();
            playlistTreeView.AutoGenerateDataBindings = true;
        }

        private void RenderControls(TreeNode selectedNode)
        {
            ContentDAO content = contentManager.GetContent(int.Parse(selectedNode.Value));
            if (content != null)
            {
                if (content.IsVideo)
                {
                    content_div_video.Visible = true;
                    content_div_practice.Visible = false;
                    contentLink = content.Video.Link;
                    BindTabBox(content.Video);
                    videoframe.DataBind();
                    selectedNode.Selected = true;

                }

                else if (content.Practice != null)
                {

                    PracticeDAO practiceDAO = new PracticeDAO();
                    practiceDAO.Id = content.Practice.Id;
                    practiceDAO.Question = content.Practice.Question;
                    practiceDAO.Answers = content.Practice.Answers;

                    Session["practice"] = practiceDAO;
                    content_div_practice.Visible = true;
                    content_div_video.Visible = false;
                    answerCheckBoxList.Enabled = false;
                    answerCheckBoxList.Items.Clear();
                    answerRadioButtonList.Items.Clear();
                    answerRadioButtonList.Enabled = false;

                    questionLabel.Text = content.Practice.Question;
                    string message = "";

                    if (contentManager.IsMultipleAnswer(content.Practice, out message))
                    {
                        answerCheckBoxList.Enabled = true;
                    }
                    else
                    {
                        answerRadioButtonList.Enabled = true;
                    }
                    selectAnswerStatementLabel.Text = message;

                    if (answerCheckBoxList.Enabled)
                    {
                        answerCheckBoxList.DataSource = content.Practice.Answers;
                        answerCheckBoxList.DataTextField = "Text";
                        answerCheckBoxList.DataValueField = "Id";
                        answerCheckBoxList.DataBind();
                    }

                    else if (answerRadioButtonList.Enabled)
                    {
                        answerRadioButtonList.DataSource = content.Practice.Answers;
                        answerRadioButtonList.DataTextField = "Text";
                        answerRadioButtonList.DataValueField = "Id";
                        answerRadioButtonList.DataBind();
                    }
                }
            }

            selectedNode.Selected = true;
        }

        private void BindTabBox(VideoContentDAO videoContentObj)
        {
            commentsTextBox.Text = "";
            commentsListView.DataSource = videoContentObj.Comments.OrderByDescending(comment=>comment.Date).ToList();
            commentsListView.DataBind();
            descriptionsListView.DataSource = videoContentObj.Descriptions;
            descriptionsListView.DataBind();
            MaterialListView.DataSource = videoContentObj.Materials;
            MaterialListView.DataBind();
            referencesListView.DataSource = videoContentObj.References;
            referencesListView.DataBind();
        }

        protected void okButton_Click(object sender, EventArgs e)
        {
            List<Answer> answers = new List<Answer>();
            if (answerCheckBoxList.Enabled)
            {
                foreach (ListItem item in answerCheckBoxList.Items)
                {
                    Answer answer = new Answer();
                    answer.Id = int.Parse(item.Value);
                    answer.IsCorrect = item.Selected ? true : false;
                    answers.Add(answer);
                }
            }
            else if (answerRadioButtonList.Enabled)
            {
                foreach (ListItem item in answerRadioButtonList.Items) ////check///
                {
                    Answer answer = new Answer();
                    answer.Id = int.Parse(item.Value);
                    answer.IsCorrect = item.Selected;
                    answers.Add(answer);
                }
            }

            PracticeDAO practice = (PracticeDAO) Session["practice"];
            string message = "";
            bool isCorrect = practiceManager.CheckIfSubmittedAnswersAreCorrect(practice, answers, out message);
            questionResponseLabel.ForeColor = isCorrect ? System.Drawing.Color.Green : System.Drawing.Color.Red;
            questionResponseLabel.Text = message;
            if (Request.IsAuthenticated)
            {
                LearnerDAO learner = userManager.GetLearnerWithName(User.Identity.Name);
                AttemptDAO attempt = new AttemptDAO();
                attempt.IsCorrect = isCorrect;
                attempt.Practice = practice;
                ScoreViewDAO score = userManager.UpdateScoreAndReturnLatestScore(learner, attempt);
                PopulateUserScore(score);
            }
        }

        protected void nextButton_Click(object sender, EventArgs e)
        {
            questionResponseLabel.Text = "";
            TreeNode selectedNode = playlistTreeView.SelectedNode;
            TreeNode nextNode =
                playlistTreeView.FindNode(contentManager.GetNextTreeNodePath(selectedNode.Value, treeDataSource.Data));
            nextNode.Selected = true;
            RenderControls(nextNode);
            RenderNextButton(nextNode);
            RenderPriviousButton(nextNode);
           
            
        }

        protected void previousButton_Click(object sender, EventArgs e)
        {
            questionResponseLabel.Text = "";
            TreeNode selectedNode = playlistTreeView.SelectedNode;
            TreeNode previousNode =
                playlistTreeView.FindNode(contentManager.GetPreviousTreeNodePath(selectedNode.Value, treeDataSource.Data));
            previousNode.Selected = true;
            RenderControls(previousNode);
            RenderNextButton(previousNode);
            RenderPriviousButton(previousNode);
        }

        protected void signOutlinkButton_Click(object sender, EventArgs e)
        {
            FormsAuthentication.SignOut();
            Response.Cache.SetNoStore();
            Response.Redirect("~/UserUI/UserHomePageUI.aspx");
        }

        protected void signUpLinkButton_Click(object sender, EventArgs e)
        {
            FormsAuthentication.RedirectToLoginPage();
        }
    }
}